import React, { useEffect, useRef, useState } from 'react';
import {EditableProTable} from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { getNavbarDetail, getShopGoodsByNavbar } from '@/services/mall/api';
import { isExits, MsgType, replaceImgHost, showMsg } from '@/utils/utils';
import { getShopGoodsByPage, getShopList } from '@/services/shop/api';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Upload, Form, Image, Tooltip, FormInstance } from 'antd';
import { miniPro } from '@/utils/constants'
// @ts-ignore
import Cookies from 'js-cookie';

const OptForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    actionRef, 
    record = {} as MALLAPI.NavbarItem
  } = props;
  const [imgVisible, setImgVisible] = useState<boolean>(false);
  const formRef = useRef<FormInstance>();
  const [form] = Form.useForm();

  // 查看图片的下标
  const [viewIndex, setViewIndex] = useState<number>(-1);

  const columns: ProColumns<any>[] = [
    {
      title: '来源店铺',
      dataIndex: 'shop_id',
      valueType: 'select',
      fieldProps: (form, {rowIndex, rowKey}) => {
        return {
          options: shopList.map(item => {
            return {
              label: item.shop_name,
              value: item.shop_id
            }
          }),
          onChange: async (value: string) => {
            const list = await fetchShopGoods(value);
            const goodsListCopy: any[] = Object.assign([], goodsList);
            goodsListCopy[rowIndex] = list;
            setGoodsList(goodsListCopy);

            const goodsItem: SHOPAPI.ShopGoods = form.getFieldsValue()[rowKey as string];
            goodsItem['goods_id'] = null;
            goodsItem['goods_name'] = null;
            goodsItem['attach_list'] = [];
            goodsItem['goods_list'] = list;
            form.setFieldsValue({ [rowKey as string]: goodsItem });
          }
        }
      }
    },
    {
      title: '商品名称',
      dataIndex: 'goods_id',
      valueType: 'select',
      fieldProps: (form, { rowIndex }) => {
        return {
          options: goodsList?.[rowIndex]?.filter(item => {
            return item.goods_status === 'O';
          }).map(item => {
            return {
              label: <Tooltip title={`【${item.brand_name}】${item.shop_goods_name}`}>
                <div style={{
                  overflow: 'hidden', 
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap'}}>【{item.brand_name}】{item.shop_goods_name}</div>
              </Tooltip>,
              value: `${item.goods_id}`
            }
          }),
          filterOption: false,
          showSearch: true,
          // onChange: (value: string) => {
            // const shopGoods = goodsList.find(item => item.goods_id === value);
            // const goodsItem: SHOPAPI.ShopGoods = form.getFieldsValue()[record.rowKey as string];
            // goodsItem['shop_id'] = shopGoods?.shop_id;
            // goodsItem['goods_id'] = value;
            // // @ts-ignore
            // goodsItem['attach_list'] =shopGoods?.attach_list;
            // const index = dataSource.findIndex(item => item.goods_name === value);
            // const list = Object.assign([], dataSource);
            // list.splice(index, 1, goodsItem);
            // setDataSource(list);
            // console.log(list);
          // }
        }
      },
      formItemProps: () => {
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            }
          ]
        }
      },
      render: (dom, entity, index) => {
        const goods = goodsList?.[index]?.find(item => item.goods_id === entity.goods_id);
        return goods ? `【${goods.brand_name}】${goods.shop_goods_name}` : ''
      }
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false
    },
    {
      title: '商品图片',
      editable: false,
      dataIndex: 'attach_list',
      render: (dom, entity, index) => {
        const attach_list = entity.attach_list?.filter(item => !item.attach_thumb_url.endsWith('.mp4'))
        if (!attach_list || !attach_list.length) {
          return '';
        }
        return <>
          <a style={{fontSize: 12}} onClick={() => {
            setImgVisible(true);
            setViewIndex(index);
          }}>查看图片</a>

          <div style={{display: 'none'}}>
            <Image.PreviewGroup preview={{ 
              visible: imgVisible && viewIndex === index, 
              onVisibleChange: vis => setImgVisible(vis) 
            }}>
              {
                attach_list?.map(item => {
                  return <Image width={100} key={item.attach_id} src={replaceImgHost(item.attach_url)}/>
                })
              }
            </Image.PreviewGroup>
          </div>
        </>
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a key="editable" onClick={() => {
          action?.startEditable?.(record.id);
        }}>编辑</a>,

        <a key="delete" onClick={() => {
          setDataSource(dataSource.filter((item) => item.id !== record.id))
        }}>删除</a>
      ]
    }
  ];

  // 店铺列表
  const [shopList, setShopList] = useState<any[]>([]);

  // 表格数据
  const [dataSource, setDataSource] = useState<SHOPAPI.ShopGoods[]>([]);

   // 编辑行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 导航详情
  const [navbarDetail, setNavbarDetail] = useState<MALLAPI.NavbarItem>({} as MALLAPI.NavbarItem);

  // 上传文件列表
  const [fileList, setFileList] = useState<any[]>([]);

  // 商品列表
  const [goodsList, setGoodsList] = useState<any[]>([]);

  // 上传的图片
  const [navImageUrl, setNavImageUrl] = useState<string>('');

  const [loading, setLoading] = useState<boolean>(false);

  // 店铺商品列表
  const fetchShopGoods = async (shop_id: string) => {
    const data = await getShopGoodsByPage({
      current: 1, 
      pageSize: 10000,
      shop_id
    });
    return data.record_list;
  }

  const fetchShopGoodsByShopIds = async (shopIds: string[]) => {
    const allRequests = [];
    shopIds.forEach(item => {
      allRequests.push(getShopGoodsByPage({
        current: 1, 
        pageSize: 10000,
        shop_id: item
      }))
    })
    Promise.all(allRequests).then((...res) => {
      const list = res[0];
      const listCopy = [];
      list.forEach(item => {
        listCopy.push(item.record_list);
      })
      setGoodsList(listCopy);
    });
  }

  useEffect(() => {
    if (record.navbar_id) {
      // 获取导航详情
      getNavbarDetail(record.navbar_id).then((data: MALLAPI.NavbarItem) => {
        // data.navbar_url = replaceImgHost(data.navbar_url || '');
        const changeUrl = replaceImgHost(data.navbar_url || '');
        setNavbarDetail(data);
        setFileList([{
          url: changeUrl,
          url1: data.navbar_url,
        }]);
        setNavImageUrl(changeUrl as string)
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });

      // 获取导航下的商品列表
      getShopGoodsByNavbar({
        current: 1,
        pageSize: 10000,
        navbar_id: record.navbar_id
      }).then(data => {
        const list = data.record_list.map((item: any) => {
          return {
            id: item.shop_goods_id,
            ...item
          }
        })
        setDataSource(list);
        fetchShopGoodsByShopIds(list?.map(item => {
          return item.shop_id;
        }));
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });
    }
  }, [record]);

  useEffect(() => {
    getShopList({
      current: 1,
      pageSize: 10000,
      shop_status: 'O'
    }).then(data => {
      setShopList(data.record_list);
    });
  }, []);

  // @ts-ignore
  const onNavIconChange = ({ file, fileList }) => {
    setFileList(fileList);
    if (file.status === 'done') {
      setFileList([
        {
          url: replaceImgHost(miniPro + file.response[0].file_web_url),
          url1: miniPro + file.response[0].file_web_url
        }
      ])
      setNavImageUrl(replaceImgHost(miniPro + file.response[0].file_web_url));
    } else if (file.status === 'error') {
      showMsg('文件上传失败');
    }
  }

  const uploadButton = (
    <div>
     <PlusOutlined />
    </div>
  );
  
  return <ModalForm
      className="modal-form"
      title="新增/编辑栏位"
      visible
      width="90%"
      scrollToFirstError
      layout="horizontal"
      modalProps={{
        maskClosable: false,
        bodyStyle: { height: window.innerHeight-150, overflow: 'scroll' }
      }}
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        try {
          await form.validateFields();
          const shop_goods_ids: string[] = [];
          dataSource.forEach(item => {
            shop_goods_ids.push(item.shop_goods_id);
            // goodsList.forEach(goods => {
            //   if (item.goods_id === goods.goods_id) {
            //     shop_goods_ids.push(goods.shop_goods_id)
            //   }
            // });
          });

          if (!fileList || !fileList[0]?.url) {
            showMsg('请上传栏位图标', MsgType.INFO);
            return;
          }
          if (loading) {
            return
          }
          setLoading(true);
          if (record.navbar_id) {
            value = Object.assign({}, value, { navbar_id: record.navbar_id, navbar_url: fileList[0].url1, shop_goods_ids});
          } else {
            value = Object.assign({}, value, { navbar_url: fileList[0].url1, shop_goods_ids});
          }
          delete value.file;
          const success = await handleAdd(value as MALLAPI.NavbarItem);
          setLoading(false);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        } catch (error) {
          setLoading(false);
          console.log(error);
        }
      }}
      submitter={isExits('500501004') ? {
        searchConfig: {
          resetText: '取消',
          submitText: '确定'
        },
        submitButtonProps: {
          loading
        }
      } : false}
      >
      <ProForm.Group>
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="栏位名称"
          width="md"
          fieldProps={{
            maxLength: 5
          }}
          name="navbar_name"
          initialValue={record.navbar_name}
        />
        <ProFormText
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="栏位排序"
          width="md"
          name="sort"
          initialValue={record.sort}
        />
      </ProForm.Group>

      <ProForm.Group>
        <Form.Item required label="栏位图标">
          <Upload 
            listType="picture-card" 
            fileList={fileList}
            headers={
              {
                'Oper-Token': localStorage.getItem('Oper-Token')
              }
            }
            showUploadList={false}
            name="file"
            accept="image/*" 
            onChange={onNavIconChange}
            action="/api/common/file/batch/upload">
              { navImageUrl ? <img src={navImageUrl} style={{ width: '100%' }} /> : uploadButton }
          </Upload>
        </Form.Item>
      </ProForm.Group>

      <div className="fz12">栏位下商品</div> 

      <ProForm.Group>
        <EditableProTable<SHOPAPI.ShopGoods>
          rowKey="id"
          formRef={formRef}
          value={dataSource}
          onChange={setDataSource}
          columns={columns}
          bordered  
          editable={{
            form,
            type: 'multiple',
            editableKeys,
            onChange: setEditableRowKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },

            onValuesChange: (record, recordList) => {
              console.log(record)
              const list = recordList.map((item, index) => {
                if (item.id === record?.id) {
                  const shopGoods = goodsList[index]?.find(g => g.goods_id === record?.goods_id);
                  console.log(shopGoods);
                  return {
                    ...item,
                    shop_goods_id: shopGoods?.shop_goods_id,
                    shop_id: shopGoods?.shop_id,
                    goods_id: record?.goods_id,
                    attach_list: shopGoods?.attach_list
                  }
                } 
                return {
                  ...item
                }
              })
              console.log(list);
              setDataSource(list as SHOPAPI.ShopGoods[]);
            }
          }}
          recordCreatorProps={
            {
              newRecordType: 'dataSource',
              record: () => {
                return {
                  id: (Math.random() * 1000000).toFixed(0)
                } as SHOPAPI.ShopGoods
              }
            }
          }
        />
      </ProForm.Group>

      <div className="modal-tips">
        <ExclamationCircleOutlined />
        <span>编辑和新增栏位信息后，请点击下方<strong>确定</strong>按钮保存结果，栏位商品来源为各店铺已上架商品</span>
      </div>
    </ModalForm>
}
export default OptForm;
